package edu.hawaii.duedates.tools;

import java.util.List;
import org.apache.wicket.util.thread.ICode;
import org.slf4j.Logger;
import edu.hawaii.duedates.datastore.ResultsList;
import edu.hawaii.duedates.datastore.LibraryChoice;

/**
 * Given user library choices, queries libraries, gathers results and emails the user. 
 * 
 * @author Daniel Arakaki, Jeho Jung, Arthur Shum, Daniel Tian.
 */
public class Alerter implements ICode {
  
  private final List<LibraryChoice> choices;
  private final String email;
  private final String smtpServer;
  
  /**
   * Constructs an Alerter with the user's library choices.
   * 
   * @param email The email address to send an alert to.
   * @param smtpServer The SMTP server to use.
   * @param choices The user's library choices.
   */
  public Alerter(String email, String smtpServer, List<LibraryChoice> choices) {
    this.email = email;
    this.smtpServer = smtpServer;
    this.choices = choices;
  }
  
  /**
   * Called periodically by the Timer to query libraries, gather results and send email to the 
   * user.
   * @param unused Unused.
   */
  public void run(Logger unused) {
    String message = "";
    for (LibraryChoice choice : this.choices) {
      try {
        ResultsList libresults = choice.getLibrary().getInfo();
        libresults.filter(choice.getFilter());
        // only add to message if there are results
        if (!libresults.isEmpty()) {
          message = message.concat("==== " + choice.getLibrary().getName() + " ===\n");
          message = message.concat(libresults.toString());          
        }
      }
      catch (Exception e) {
        // info(e.getMessage());
        message = message.concat("==== " + choice.getLibrary().getName() + " ===\n");
        message = message.concat("Unable to get results.\n\n");
        continue;
      }
    }

    // only send email if there is a message
    if (message.length() > 0) {
      // System.out.println(message);
      DueDatesMail mailer = DueDatesMail.getInstance();
      try {
        mailer.sendMail(this.email, this.smtpServer, message);        
      }
      catch (Exception e) {
        unused.error(e.getMessage());
      }
    }
    
  }
  
}
